//
//  FilterCriteriaViewController.swift
//  月升
//
//  Created by 拉利法 on 2024/7/10.
//  筛选条件

import UIKit

class FilterCriteriaViewController: QIBaseViewController {
    
    /// 预览图片
    var previewImg = UIImage()
    /// 原图在本地服务器地址
    var originalImgUrl = ""
    /// 原图地址
    var raw_file_path = ""
    /// 时间名称
    var event_name = ""
    /// 五官检测结果
    var wuGuanModel = QIFiveSensesResultModel()
    private var imgPreviewView = UIImageView()
    private var dataArr = [QIFacialFeaturesModel]()
    /// 化妆场景
    private var occasion = "1,1,1,1,1"
    /// 化妆时间
    private var time = "1,1,1"
    /// 妆容包含
    private var includes = "1,1,1,1,1,1,1,1,1,1,1"
    /// 妆容强调
    private var emphasis = "1,1,1,1,1,1,1,1,1,1,1"
    /// 美妆视频推荐列表
    private var recommenListModelArr = [QIBeautyRecommenListModel]()
    private var vDataDict = [String: JSON]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "美妆推荐"
        dataArr = [
            QIFacialFeaturesModel(title: "场景", value: "不限"),
            QIFacialFeaturesModel(title: "视频长度", value: "不限"),
            QIFacialFeaturesModel(title: "妆容要求", value: "不限")
        ]

        addUI()
        getVData()
    }
    

    
    private func addUI() {
        showGradientColor()
        
        imgPreviewView = UIImageView().then {
            $0.frame = CGRect(x: 15, y: NAV_HEIGHT, width: SCREEN_WIDTH - 30, height: 410)
            $0.image = previewImg
            $0.tag = 11
            $0.contentMode = .scaleAspectFill
            $0.clipsToBounds = true
            $0.addRoundedCorners(withRadius: 10)
        }
        view.addSubview(imgPreviewView)
        
        let titleL = UILabel().then({
            $0.frame = CGRect(x: 15, y: imgPreviewView.bottom + 10, width: 100, height: 22)
            $0.text = "筛选条件"
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 16)
        })
        view.addSubview(titleL)
        
        collectionView.frame = CGRect(x: 15, y: titleL.bottom + 10, width: SCREEN_WIDTH - 30, height: 150)
        view.addSubview(collectionView)
        
        let nextBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 75, y: collectionView.bottom + 20, width: 150, height: 36)
            $0.backgroundColor = ColorWithStr("#FFD5DA")
            $0.titleLabel?.font = FONT(ofSize: 16)
            $0.setTitle("推荐化妆视频", for: .normal)
            $0.setTitleColor(MainColor, for: .normal)
            $0.addRoundedCorners(withRadius: 18)
            $0.addTarget(self, action: #selector(videoBtnClick), for: .touchUpInside)
        }
        view.addSubview(nextBtn)
        
    }
    
    
    private func getVData() {
        QINetworkManager.requestJson(urlStr: "/Skin/video_details", parameters: nil) { json in
            print(json)
            self.vDataDict = json.dictionaryValue
        }
        
    }
    
    private func getData() {
        let url = "http://124.222.206.164:9000/develop_recommend_2"
        let param = [
            "facial_data_code_string": wuGuanModel.facial_data_code_string,
            "occasion": occasion,
            "time": time,
            "includes": includes,
            "emphasis": emphasis
        ]
        QINetworkManager.requestJson(urlStr: url, parameters: param, isJson: true) { json in
            print(json)
            
            let arr = json.arrayValue
            for jj in arr {
                var model = jj.dictionaryObject?.kj.model(QIBeautyRecommenListModel.self) ?? QIBeautyRecommenListModel()
                model.title = model.makeup_type.joined(separator: "/")
                
                if self.vDataDict.keys.contains(model.video_code) {
                    let j = self.vDataDict[model.video_code]
                    let m = j?.dictionaryObject?.kj.model(QIBeautyRecommenChildListModel.self) ?? QIBeautyRecommenChildListModel()
                    model.vModel = m
                }
                self.recommenListModelArr.append(model)
            }
            
            
            
            let ctl = FilterCriteriaVideoListViewController()
            ctl.recommenListModelArr = self.recommenListModelArr
            ctl.previewImg = self.previewImg
            ctl.event_name = self.event_name
            ctl.wuGuanModel = self.wuGuanModel
            ctl.raw_file_path = self.raw_file_path
            ctl.originalImgUrl = self.originalImgUrl
            self.navigationController?.pushViewController(ctl, animated: true)
            print("")
        }
    }
    
    @objc private func videoBtnClick() {
        getData()
    }
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 1
        flowLayout.minimumInteritemSpacing = 1
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(FilterCriteriaViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        
        return collectionView
    }()

}

extension FilterCriteriaViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellW = (SCREEN_WIDTH - 55) / 3
        return CGSize(width: cellW, height: 150)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FilterCriteriaViewCell
        cell.backgroundColor = UIColor.white
        if dataArr.count > indexPath.row {
            cell.model = dataArr[indexPath.row]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            let vv = SelectSceneFilterCriteriaView(frame: CGRect(x: 65, y: NAV_HEIGHT + 128, width: SCREEN_WIDTH - 130, height: 200))
            vv.backgroundColor = UIColor(white: 0, alpha: 0.56)
            vv.selectStrArrBlock = { arr in
                self.dataArr[indexPath.row].value = arr.joined(separator: "\n")
                collectionView.reloadData()
            }
            vv.selectStatusStringBlock = { str in
                self.occasion = str
            }
            QINPopUpTool.sharedInstance().popUp(with: vv, withAnimation: .none, withCanTapBgCancel: true, closeBefore: .close, bgColor: .clear)
        } else if indexPath.row == 1 {
            let alertCtl = UIAlertController(title: "视频长度", message: nil, preferredStyle: .actionSheet)
            alertCtl.addAction(UIAlertAction(title: "长", style: .default, handler: { (_) in
                self.dataArr[indexPath.row].value = "长"
                self.time = "1,0,0"
                collectionView.reloadData()
            }))
            alertCtl.addAction(UIAlertAction(title: "中", style: .default, handler: { (_) in
                self.dataArr[indexPath.row].value = "中"
                self.time = "0,1,0"
                collectionView.reloadData()
            }))
            alertCtl.addAction(UIAlertAction(title: "短", style: .default, handler: { (_) in
                self.dataArr[indexPath.row].value = "短"
                self.time = "0,0,1"
                collectionView.reloadData()
            }))
            alertCtl.addAction(UIAlertAction(title: "不限", style: .default, handler: { (_) in
                self.dataArr[indexPath.row].value = "不限"
                self.time = "0,0,0"
                collectionView.reloadData()
            }))
            alertCtl.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in
                
            }))
            self.present(alertCtl, animated: true)
        } else if indexPath.row == 2 {
            let vv = SelectMakeupFilterCriteriaView(frame: CGRect(x: 65, y: NAV_HEIGHT + 128, width: SCREEN_WIDTH - 130, height: 310))
            vv.backgroundColor = UIColor(white: 0, alpha: 0.56)
            vv.selectStringBlokc = { str in
                self.dataArr[indexPath.row].value = str
                collectionView.reloadData()
            }
            vv.selectstatusStr1 = { str in
                self.includes = str
            }
            vv.selectstatusStr2 = { str in
                self.emphasis = str
            }
            QINPopUpTool.sharedInstance().popUp(with: vv, withAnimation: .none, withCanTapBgCancel: true, closeBefore: .close, bgColor: .clear)
            
        }
        
    }
    
}



class FilterCriteriaViewCell: UICollectionViewCell {
    
    private var topLabel = UILabel()
    private var colorNameLabel = UILabel()
    private var bottomLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
//        self.addRoundedCorners(withRadius: 10)
        self.layer.cornerRadius = 10
        addUI()
    }
    
    private func addUI() {
        topLabel = UILabel().then({
            $0.frame = CGRect(x: 10, y: 8, width: self.width, height: 17)
            $0.text = ""
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 12)
        })
        self.addSubview(topLabel)
        
        colorNameLabel = UILabel().then({
            $0.frame = CGRect(x: 10, y: topLabel.bottom + 2, width: self.width - 20, height: 30)
            $0.text = ""
            $0.numberOfLines = 2
            $0.textColor = Color333333
            $0.font = FONTBOLD(ofSize: 12)
        })
        self.addSubview(colorNameLabel)
        
        bottomLabel = UILabel().then({
            $0.frame = CGRect(x: 10, y: colorNameLabel.bottom + 5, width: self.width - 20, height: self.height - 80)
            $0.text = ""
            $0.numberOfLines = 0
            $0.textColor = Color333333
            $0.textAlignment = .center
            $0.font = FONT(ofSize: 15)
        })
        self.addSubview(bottomLabel)
    }
    
    var model = QIFacialFeaturesModel() {
        didSet {
            topLabel.text = model.title
            colorNameLabel.text = model.colorName
            bottomLabel.text = model.value
            if model.value == "不限" {
                bottomLabel.textColor = Color666666
            } else {
                bottomLabel.textColor = MainColor
            }
            if model.bgColor != UIColor.white {
                self.backgroundColor = model.bgColor
                topLabel.textColor = .white
                colorNameLabel.textColor = .white
                bottomLabel.textColor = .white
            } else if model.type == "偏好选择" {
                topLabel.textColor = Color333333
                colorNameLabel.textColor = Color333333
                bottomLabel.textColor = Color333333
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
